import React from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { createForm } from 'rc-form';
import cx from 'classnames';
import { WingBlank, WhiteSpace, Flex, List, Button, Toast } from 'antd-mobile';
import styles from '../scale/styles.less';
import { SCALE_PHY , SCALE_PHY2 } from 'const';

function ScalePhyTemplate({ dispatch, location, form, questions, scalevalue, detail, ...rest }) {
  const { state, query } = location;
  const { type, patientid, step, patientvalue, ss } = location.state;
  const { getFieldProps, getFieldValue, setFieldsValue, validateFields, getFieldError } = form;
  let question, quLength;

  if(type == 'phy'){
    question = SCALE_PHY[step];
    quLength = 43;
  }else if(type == 'phy2'){
    question = SCALE_PHY2[step];
    quLength = 103;
  }
  const isNativeApp = location.pathname.indexOf('/scale_phy') !== -1 && query.s === 'app';

  if (!Object.keys(scalevalue).length) {
    scalevalue = [[], []];
    dispatch({ type: 'scale/save', payload: { scalevalue } });
  }

  let infos = scalevalue[0] || []; //用户信息
  let scores = scalevalue[1] || []; //症状

  let nextStep = step + 1;
  const category = step - 2;

  let stepQuestions = [];
  if(type == 'phy'){
   if (category >= 0 && category < 42) {
     stepQuestions = SCALE_PHY[category].subject;
   }  
  }else if(type == 'phy2'){
   if (category >= 0 && category < 102) {
     stepQuestions = SCALE_PHY2[category].subject;
   }  
  }

  const validateForm = () => {
    validateFields((err, values) => {
      if (err) {
        const fieldNames = Object.keys(err);
        if (fieldNames[0]) {
          return Toast.fail(getFieldError(fieldNames[0]));
        }
      } else {
          Object.keys(values).forEach((key) => {
            if (values[key]) {
              // scores.push(key);
            }
          });

        dispatch({ type: 'scale/save', payload: { scalevalue: [infos, scores] } });

        if (nextStep <= quLength -1 ) {
          // '下一页'
          let pathname = location.pathname;
          if (isNativeApp) {
            pathname = `${location.pathname}?s=${query.s}&doctorid=${query.doctorid}&memberid=${query.memberid}`;
            
          }
          dispatch(
            routerRedux.replace({
              pathname,
              state: {
                type,
                patientid,
                step: nextStep,
              },
            }),
          );
        } else {
          // 最后一页'提交'
          if(scores.length < quLength){
              return Toast.fail('请完成所有题目', 1);
          }else{
             if(scores[quLength -1] !== ""){
                 for(var i = 0 ;i<scores.length;i++){
                   if(scores[i] == "" || typeof(scores[i]) == "undefined" ) {
                       return Toast.fail('请完成所有题目', 1);
                   }
                 }
              }
              const patientValue = `${scores.join('')}`;
              dispatch({
                type: 'scale/submitQuestions',
                payload: {
                  type: location.state.type,
                  patientId: state.patientid,
                  familyId: JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid"))).patientId,
                  patientValue,
                  ...rest,
                },
              });
          }
        }
      }
    });
  };

  function isActive(key, value, i,name) {

    if (scores[i]&&scores[i]===value) {
      return true;
    }
    if (!getFieldValue(key)) {
      return false;
    }

    if(getFieldValue(key) !==value){
      return false;
    }
    return getFieldValue(key) === value;
  }

  function handleChange({ target: { type, name, value } }) {
    name = name - 1;
    if(scores[name]){
        setFieldsValue({ [name]: value });
        scores[name] = value;
        dispatch({ type: 'scale/save', payload: { scalevalue: [infos, scores] } });
        return;
    }

    if (getFieldValue(name) === value) {

    } else {
        setFieldsValue({ [name]: value });
        if(scores.length <= quLength ){
          scores[name] = value;
        }
        // else{
        //   scores.splice(scores.length-1,1);
        //   scores[name] = value;
        // }
    }
    dispatch({ type: 'scale/save', payload: { scalevalue: [infos, scores] } });
  }
  
  function nextHandler() {
    if(step<quLength-1){
    window.scrollTo(0, 0);
    nextStep = step + 1;
    
      validateForm();
    }
  }

  function prevHandler() {
    window.scrollTo(0, 0);
    nextStep = step - 1;
    validateForm();
  }

  var clickNum=1;
  function submitHandler() {
    if(clickNum){
      Toast.loading('正在加载');
      clickNum= 0;
      nextStep = step + 1;
      validateForm();
    }
  }

  return (
    <WingBlank size="sm">
      <WhiteSpace />
      <List>
        <List.Item>
           <Flex justify="center" style={{marginTop: '0.1rem'}}>请您仔细阅读题目，凭第一感觉尽快、如实地回答</Flex>
           <Flex justify="center">不需费时间考虑，尽量不要修改</Flex>
           <Flex justify="center">全部符合您的情况时答"是",只有部分符合只能答"否"</Flex>
        </List.Item>
        <List.Item wrap multipleLine >
            {`${step+1}. ${question.Title}`}
            <List.Item.Brief>
              <Flex justify="between">
                {question.Choicekey.split('|').map((option, ii) => {
                  const value = question.Choicevalue.split('|')[ii];
                  const key = question.Id;
                  return (
                    <Flex.Item key={value}>
                      <label
                        className={cx(styles.questionOption, styles.questionOptionNormal, {
                          [styles.questionOptionActive]: isActive(key, value, step),
                        })}
                      >
                        <input {...getFieldProps(`${key}`)} type="radio" name={key} value={value} checked={isActive(key, value, step,name)} onClick={nextHandler} onChange={handleChange} required />
                        {option}
                      </label>
                    </Flex.Item>
                  );
                })}
              </Flex>
            </List.Item.Brief>
          </List.Item>

        {!Object.keys(detail).length
          ? <div>
            <WhiteSpace size="xl" />
            <WingBlank>
                <Flex>
              {step === 0
                ? null
                : <Flex.Item>
                  <Button onClick={prevHandler}>上一页</Button>
                </Flex.Item>}

              {step < quLength - 1
                ? <Flex.Item>
                  <Button type="primary" onClick={nextHandler}>下一页</Button>
                  </Flex.Item>
                : <Flex.Item>
                  <Button type="primary" onClick={submitHandler}>提交</Button>
                </Flex.Item>}

            </Flex>
              </WingBlank>
            <WhiteSpace size="xl" />
          </div>
          : null}
      </List>
      <WhiteSpace size="xl" />
    </WingBlank>
  );
}

export default connect(({ scale }) => ({ ...scale }))(createForm()(ScalePhyTemplate));
